﻿using System.Linq;
using CID.Domain.Infrastructure;
using CID.Tests.Support;
using NUnit.Framework;

namespace CID.Domain.Persistence.Tests.Infrastructure
{
    [TestFixture]
    class PackagePersistenceTests : BasePersistenceWithDataTests
    {
        private static void AssertAreEqual(Package expected, Package actual)
        {
            Assert.AreEqual(expected.Id, actual.Id);
            Assert.AreEqual(expected.Version.Id, actual.Version.Id);
            Assert.AreEqual(expected.Content, actual.Content);
            Assert.AreEqual(expected.Comment, actual.Comment);
            Assert.AreEqual(expected.Type.Id, actual.Type.Id);
        }

        [Test]
        public void SaveNewPackage_PackageShouldBeSaved()
        {
            var session = OpenSession();
            var newPackage = DataProvider.CreatePackage(session, InfrastructureData.PackageType, DevelopmentData.Component1UnreleasedVersion);
            session.SaveOrUpdate(newPackage);
            CleanSession(session);

            Assert.AreNotEqual(NotSavedId, newPackage.Id);
            session = OpenSession();
            var retrievedPackage = session.Get<Package>(newPackage.Id);
            AssertAreEqual(newPackage, retrievedPackage);
            CleanSession(session);
        }

        [Test]
        public void DeletePackage_PackageShouldBeDeleted()
        {
            var session = OpenSession();
            var newPackage1 = DataProvider.CreatePackage(session, InfrastructureData.PackageType, DevelopmentData.Component1UnreleasedVersion);
            var newPackage2 = DataProvider.CreatePackage(session, InfrastructureData.PackageType, DevelopmentData.Component2UnreleasedVersion); 
            session.SaveOrUpdate(newPackage1);
            session.SaveOrUpdate(newPackage2);
            CleanSession(session);

            session = OpenSession();
            var retrievedPackage1 = session.Get<Package>(newPackage1.Id);
            session.Delete(retrievedPackage1);
            CleanSession(session);

            session = OpenSession();
            retrievedPackage1 = session.Get<Package>(newPackage1.Id);
            var retrievedPackage2 = session.Get<Package>(newPackage2.Id);
            Assert.IsNull(retrievedPackage1);
            Assert.IsNotNull(retrievedPackage2);
            CleanSession(session);
        }
    }
}
